dojo.provide("dojoscratch.Scaler");
//based on http://archive.dojotoolkit.org/nightly/checkout/dojox/gfx/Mover.js
dojo.declare("dojoscratch.Scaler", null, {
	constructor: function(shape, e, host){
	// summary: an object, which makes a shape follow the mouse,
	//	used as a default scaler, and as a base class for custom scalers
	// shape: dojox.gfx.Shape: a shape object to be scaled
	// e: Event: a mouse event, which started the scale;
	//	only clientX and clientY properties are used
	// host: Object?: object which implements the functionality of the scale,
	//	 and defines proper events (onScaleStart and onScaleStop)
	this._shape = shape;
	this._lastX = e.clientX
	this._lastY = e.clientY;
	var h = this.host = host, d = document,
		firstEvent = dojo.connect(d, "onmousemove", this, "_onFirstScale");
	this._events = [
		dojo.connect(d, "onmousemove", this, "_onMouseMove"),
		dojo.connect(d, "onmouseup",   this, "destroy"),
		// cancel text selection and text dragging
		dojo.connect(d, "ondragstart",   dojo, "stopEvent"),
		dojo.connect(d, "onselectstart", dojo, "stopEvent"),
		firstEvent
	];
	// notify that the scale has started
	if(h && h.onScaleStart){
		h.onScaleStart(this);
	}
},
// mouse event processors
_onMouseMove: function(e){
	// summary: event processor for onmousemove
	// e: Event: mouse event
	var x = e.clientX;
	var y = e.clientY;
	this.host.onScale(this, {dx: x - this._lastX, dy: y - this._lastY});
	this._lastX = x;
	this._lastY = y;
	dojo.stopEvent(e);
},
// utilities
_onFirstScale: function(){
	// summary: it is meant to be called only once
	this.host.onFirstScale(this);
	dojo.disconnect(this._events.pop());
},
destroy: function(){
	// summary: stops the scale, deletes all references, so the object can be garbage-collected
	dojo.forEach(this._events, dojo.disconnect);
	// undo global settings
	var h = this.host;
	if(h && h.onScaleStop){
		h.onScaleStop(this);
	}
	// destroy objects
	this._events = null;
	this._shape = null;
}
});
